package com.xs.ahoi.hcxs.ui.dialog;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.utils.Constants;
import com.xs.ahoi.hcxs.utils.FileUtil;
import com.xs.ahoi.hcxs.utils.StringUtils;
import com.xs.ahoi.hcxs.utils.ThreadPoolFactory;
import com.xs.ahoi.hcxs.utils.ToastUtil;
import com.xs.ahoi.hcxs.utils.ViewUtil;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 选中文字替换弹窗页面
 */
public class DialogReplace extends BaseDialog {

    @BindView(R.id.etOldText)
    public EditText etOldText;
    @BindView(R.id.etNewText)
    public EditText etNewText;
    @BindView(R.id.ivRIndex)
    public ImageView ivRIndex;
    @BindView(R.id.rIndexLayout)
    public AutoLinearLayout rIndexLayout;
    @BindView(R.id.ivReg)
    public ImageView ivReg;
    @BindView(R.id.ivIgnore)
    public ImageView ivIgnore;
    @BindView(R.id.tvRIndex)
    public TextView tvRIndex;
    @BindView(R.id.tvReg)
    public TextView tvReg;
    @BindView(R.id.tvIgnore)
    public TextView tvIgnore;
    @BindView(R.id.tvTips)
    public TextView tvTips;
    @BindView(R.id.mFlowLayout)
    public TagFlowLayout mFlowLayout;
    @BindView(R.id.regTextGroup)
    public ScrollView regTextGroup;

    private ReplaceListener listener;
    // 替换前的文字内容，即为选中文字
    private String oldText;
    private boolean etOldTextFocus = false;
    private boolean etNewTextFocus = false;
    // 选中和未选中时图标
    private Drawable drawableNormal, drawableChecked;
    // 选中和未选中时文字颜色
    private int colorCheck, colorNormal;
    // 追加序号是否选中
    private boolean rIndexCheck = false;
    // 正则匹配是否选中
    private boolean regCheck = false;
    // 忽略大小写是否选中
    private boolean ignoreCheck = false;
    private Handler mHandler;
    private LayoutInflater mInflater;
    private final String[] regTexts = {"删", ".", "*", "\\", "+", "<", ">", "(", ")", "[", "]", "{", "}", "^", "$", ";"};

    public DialogReplace(Context context) {
        super(context, R.style.common_dialog);
    }

    @Override
    public int getLayoutRes() {
        return R.layout.dialog_replace;
    }

    @Override
    protected int showPosition() {
        return Gravity.CENTER;
    }

    @Override
    @SuppressLint("HandlerLeak")
    protected void initData() {
        drawableNormal = ContextCompat.getDrawable(getContext(), R.drawable.icon_rect_uncheck);
        drawableChecked = ContextCompat.getDrawable(getContext(), R.drawable.icon_rect_check);

        colorNormal = ContextCompat.getColor(getContext(), R.color.colorBlackLittle);
        colorCheck = ContextCompat.getColor(getContext(), R.color.colorRed);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        if (msg.arg2 == 1) {
                            ToastUtil.show("替换成功");
                            tvTips.setText(getContext().getString(R.string.replace_success).replace("{count}", msg.arg1 + ""));
                        } else {
                            ToastUtil.show("计数成功");
                            tvTips.setText(getContext().getString(R.string.count_success).replace("{count}", msg.arg1 + ""));
                        }

                        Constants.canReplace = false;
                        tvTips.setVisibility(View.VISIBLE);
                        listener.hideLoading();
                        // 更新书籍信息
                        BookFactory.getInstance().updateBookInfo();
                        // 重新断章
                        BookFactory.getInstance().startCatalogs(true);
                        break;
                }
            }
        };

        // 自动换行布局
        mInflater = LayoutInflater.from(getContext());
        mFlowLayout.setAdapter(new TagAdapter<String>(regTexts) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                AutoRelativeLayout arl = (AutoRelativeLayout) mInflater.inflate(R.layout.flow_layout_reg_text, mFlowLayout, false);
                TextView tv = arl.findViewById(R.id.tvTag);
                tv.setText(s);
                return arl;
            }
        });
        mFlowLayout.setOnTagClickListener((view, position, parent) -> {
            if (position == 0) {
                ViewUtil.deleteText(etOldText);
            } else {
                ViewUtil.insertText(etOldText, regTexts[position]);
            }
            return true;
        });

        // EditText焦点改变事件
        etOldText.setOnFocusChangeListener((view, hasFocus) -> {
            etOldTextFocus = hasFocus;
            toggleRegTextGroup();
        });

        // EditText焦点改变事件
        etNewText.setOnFocusChangeListener((view, hasFocus) -> {
            etNewTextFocus = hasFocus;
            toggleRegTextGroup();
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
        tvTips.setVisibility(View.GONE);
        etOldText.setText(oldText);
        if (StringUtils.isNotEmpty(oldText)) {
            etOldText.setSelection(oldText.length());
        }
    }

    @OnClick({R.id.tvDialogCount, R.id.tvDialogOk, R.id.tvDialogCancel,
            R.id.rIndexLayout, R.id.regMatch, R.id.ignoreCase})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvDialogCount:
                startReplace(false);
                break;
            case R.id.tvDialogOk:
                if (StringUtils.isNotEmpty(etOldText.getText().toString())) {
                    startReplace(true);
                } else {
                    ToastUtil.show("请先输入替换内容");
                }
                break;
            case R.id.tvDialogCancel:
                super.dismiss();
                break;
            case R.id.rIndexLayout:
                if (rIndexCheck) {
                    setUnCheck(ivRIndex, tvRIndex);
                } else {
                    setCheck(ivRIndex, tvRIndex);
                }
                rIndexCheck = !rIndexCheck;
                toggleRIndexFlag();
                break;
            case R.id.regMatch:
                if (regCheck) {
                    setUnCheck(ivReg, tvReg);
                } else {
                    setCheck(ivReg, tvReg);
                }
                regCheck = !regCheck;
                toggleRegTextGroup();
                break;
            case R.id.ignoreCase:
                if (ignoreCheck) {
                    setUnCheck(ivIgnore, tvIgnore);
                } else {
                    setCheck(ivIgnore, tvIgnore);
                }
                ignoreCheck = !ignoreCheck;
                break;
        }
    }

    // 显示隐藏正则按钮栏组
    private void toggleRegTextGroup() {
        if (etOldTextFocus) {
            if (regCheck) {
                regTextGroup.setVisibility(View.VISIBLE);
            } else {
                regTextGroup.setVisibility(View.GONE);
            }
        }
        if (etNewTextFocus) {
            rIndexLayout.setVisibility(View.VISIBLE);
        } else {
            rIndexLayout.setVisibility(View.GONE);
        }
    }

    private void toggleRIndexFlag() {
        if (rIndexCheck) {
            ViewUtil.insertText(etNewText, Constants.REPLACE_INDEX);
        } else {
            String text = etNewText.getText().toString();
            int i = text.indexOf(Constants.REPLACE_INDEX);
            if (i > -1) {
                etNewText.setText(text.replace(Constants.REPLACE_INDEX, ""));
                etNewText.setSelection(i);
            }
        }
    }

    // 开始替换
    private void startReplace(boolean isReplace) {
        listener.showLoading(isReplace ? getContext().getString(R.string.replace_ing) : getContext().getString(R.string.count_ing));
        tvTips.setVisibility(View.GONE);
        Constants.canReplace = true;
        ThreadPoolFactory.getInstance().execute(() -> {
            int count = FileUtil.replaceContent(BookFactory.getInstance().getBookPath(),
                    etOldText.getText().toString(),
                    etNewText.getText().toString(),
                    isReplace,
                    regCheck,
                    ignoreCheck);
            Message message = new Message();
            message.what = 1;
            message.arg1 = count;
            message.arg2 = isReplace ? 1 : 0;
            mHandler.sendMessage(message);
        });
    }

    // 设置选中后的样式
    private void setCheck(ImageView iv, TextView tv) {
        iv.setImageDrawable(drawableChecked);
        tv.setTextColor(colorCheck);
    }

    // 设置取消选中后的样式
    private void setUnCheck(ImageView iv, TextView tv) {
        iv.setImageDrawable(drawableNormal);
        tv.setTextColor(colorNormal);
    }

    public void setOldText(String oldText) {
        this.oldText = oldText;
    }

    public void setListener(ReplaceListener listener) {
        this.listener = listener;
    }

    public interface ReplaceListener {
        void showLoading(String text);

        void hideLoading();
    }
}
